package review;

import java.util.Arrays;

public class test2 {
    private int[] arr;
    private int size;

    public test2(){
        this(10);
    }
    public test2(int initCap){
        this.arr=new int[initCap];
    }


    public static void main(String[] args) {
        test2 array=new test2(5);
        array.addVal(1);
        array.addVal(2);
        array.addVal(3);
        System.out.println(array);
        array.addIndex(0,1);
        array.addIndex(4,4);
        System.out.println(array);
        System.out.println(array.getVal(10));
        System.out.println(array.contain(10));
        System.out.println(array.get(3));
    }



    public int get(int index){
        //查询索引为index的元素
        if (index<0||index>=size){
            System.err.println("index不在范围内");
            return -1;
        }
        return arr[index];

    }
    public boolean contain(int val){
        //查询是否包含
       int index=getVal(val);
        return index!=-1;
    }

    public int getVal(int val){
        //查找第一个值为val
        for (int i = 0; i < size; i++) {
            if (arr[i]==val){
                return i;
            }
        }return -1;
    }

    public void addIndex(int index,int val){
        //索引插入
        if (index<0||index>size){
            System.err.println("index不在范围内");
        }
        for (int i = size-1; i >=index; i--) {
            arr[i+1]=arr[i];
        }
        arr[index]=val;
        size++;
        if (size== arr.length){
            grow();
        }
    }

    public void addVal(int val){
        //默认尾插
        arr[size]=val;
        size++;
        if (size== arr.length){
            grow();
        }
    }
    private void grow(){
        arr=Arrays.copyOf(arr,arr.length*2);
    }


    public String toString(){
        //打印方法
       String ret="[";
        for (int i = 0; i < size; i++) {
            ret+=arr[i];
            if (i!=size-1){
                ret+=',';
            }
        }
        ret+="]";
        return ret;
    }

}
